package com.namlh.products.cms.services.dao;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.namlh.products.cms.services.domain.User;

public class UserDaoImpl implements UserDao {

	private EntityManager entityManager;

	public void setEm(EntityManager em) {
		this.entityManager = em;
	}

	public User findByUserId(String userId) {
		return entityManager.find(User.class, userId);
	}

	public User findByUserName(String userName) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<User> criteria = cb.createQuery(User.class);
		Root<User> user = criteria.from(User.class);

		/*
		 * Swap criteria statements if you would like to try out type-safe
		 * criteria queries, a new feature in JPA 2.0
		 * criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
		 */

		criteria.select(user).where(cb.equal(user.get("userName"), userName));
		return entityManager.createQuery(criteria).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	public Set<User> findAllOrderedByName() {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<User> criteria = cb.createQuery(User.class);
		Root<User> user = criteria.from(User.class);

		/*
		 * Swap criteria statements if you would like to try out type-safe
		 * criteria queries, a new feature in JPA 2.0
		 * criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
		 */

		criteria.select(user).orderBy(cb.asc(user.get("userName")));
		return (Set<User>) entityManager.createQuery(criteria).getResultList();
	}

	public void addUser(User user) {
		entityManager.getTransaction().begin();
		
		if (entityManager.contains(user)) {
			entityManager.merge(user);
		} else {
			entityManager.persist(user);
		}
		
		entityManager.getTransaction().commit();
	}

	public void editUser(User user) {
		// TODO Auto-generated method stub

	}

	public void deleteUser(User user) {
		// TODO Auto-generated method stub

	}

}
